package com.zerui.manager.app.devicegroup.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.BizException;
import com.zerui.cola.dto.Response;
import com.zerui.manager.devicegroup.DeviceGroup;
import com.zerui.manager.devicegroup.domainservice.DeviceGroupRepository;
import com.zerui.manager.web.cmd.DeviceGroupAddCmd;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author wh
 * @create_time 2023-08-23 16:29
 */
@Component
@CatchAndLog
public class DeviceGroupAddCmdExe {

    @Resource
    private DeviceGroupRepository deviceGroupRepository;

    public Response execute(DeviceGroupAddCmd deviceGroupAddCmd) {

        DeviceGroup root = deviceGroupRepository.selectById(deviceGroupAddCmd.getSupId());
        if(ObjectUtils.isEmpty(root) || !DeviceGroup.isRootName(root.getOrgName())){
            throw new BizException("新增节点上级节点必须是根节点");
        }
        DeviceGroup group = deviceGroupRepository.getNodeByName(deviceGroupAddCmd.getOrgName());
        if(ObjectUtils.isNotEmpty(group)){
            throw new BizException("节点名称重复");
        }
        deviceGroupRepository.addDeviceGroup(
                DeviceGroup.create(
                        null,
                        deviceGroupAddCmd.getOrgName(),
                        deviceGroupAddCmd.getSupId(),
                        null,
                        null,
                        null
                )
        );
        return Response.buildSuccess();
    }

    @EventListener(ContextRefreshedEvent.class)
    public void initRootNode(){
        DeviceGroup group = deviceGroupRepository.getNodeByName(DeviceGroup.ROOT_NODE_NAME);
        if(ObjectUtils.isEmpty(group)){
            deviceGroupRepository.addDeviceGroup(
                    DeviceGroup.create(
                            null,
                            DeviceGroup.ROOT_NODE_NAME,
                            null,
                            null,
                            null,
                            null
                    )
            );
        }
    }

}
